package goroutine

import (
	"bytes"
	"time"

	"gitee.com/doraemon1996/bunny/log"
	"gitee.com/doraemon1996/bunny/utils"
)

// 工作协程
type worker struct {
	// 协程池
	goPool *GoPool

	// 工作任务获取通道
	// 任务应该有执行结束的时候
	pipe chan func()

	// 协程空闲时间
	idleTime time.Time
}

// 工作协程的运行逻辑
func (w *worker) run() {
	w.goPool.ctl.Add(1)
	w.goPool.addRunning(1)

	go func() {
		defer func() {
			if err := recover(); err != nil {
				buf := new(bytes.Buffer)
				utils.StackTraceback(2, buf)
				log.Errorf("the worker caught a panic error: %v\n%s", err, buf.String())
			}

			w.goPool.addRunning(-1)
			w.goPool.ctl.Done()
			w.goPool.workerPool.Put(w)
			w.goPool.cond.Signal()
		}()

		for task := range w.pipe {
			// 主动退出协程
			if task == nil {
				return
			}

			task()

			if w.goPool.putWorker(w) {
				return
			}
		}
	}()
}
